package GroupChat;/*

 */

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.channels.Pipe;
import java.security.PublicKey;

/**
 * @ClassName GroupChatServer
 * @Author Final
 * @Project DataStructures
 */
public class GroupChatServer {

    private int port;

    public GroupChatServer(int port){
        this.port=port;
    }

    //编写run方法，处理客户端请求
    public void run() throws InterruptedException {

        //创建两个group组
        NioEventLoopGroup boosGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {

        ServerBootstrap bootstrap = new ServerBootstrap();

        bootstrap.group(boosGroup,workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG,128).childOption(ChannelOption.SO_KEEPALIVE,true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        //获取到pipeline
                        ChannelPipeline pipeline = socketChannel.pipeline();

                        //向pipeline加入解码器
                        pipeline.addLast("decoder",new StringDecoder());

                        pipeline.addLast("encoder",new StringEncoder());
                        //加入自己的业务处理Handel
                        pipeline.addLast(new GroupChatServerHandler());
                    }
                });

        System.out.println("netty服务器启动");
        ChannelFuture sync = bootstrap.bind(port).sync();

        //监听关闭事件
        sync.channel().closeFuture().sync();

        }finally {
            boosGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }


    public static void main(String[] args) throws InterruptedException {

        new GroupChatServer(7000).run();
    }
}
